/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dksoft.controller;

import com.dksoft.model.CalendarMethod;
import java.io.InputStream;
import java.sql.*;
import org.apache.log4j.Logger;

/**
 *
 * @author Dickson
 */
public class RunScript {

    private static Logger logger = Logger.getLogger(RunScript.class.getName());
    private String scriptUrl = "/Database/Script.sql";

    public boolean execute() {
        boolean isSuccessPath = false;
        if (isFileExist(scriptUrl) == true) {
            try {
                Class.forName("org.h2.Driver");
                StringBuilder connectionBuilder = new StringBuilder();
                connectionBuilder.append("jdbc:h2:file:");
                connectionBuilder.append(CalendarMethod.getDBPath());
                connectionBuilder.append(Constant.DB_NAME);
                connectionBuilder.append(";FILE_LOCK=NO;IFEXISTS=TRUE;MODE=MSSQLServer");
                //jdbc:h2:file:C:/nageIT/Calendar;FILE_LOCK=NO;IFEXISTS=TRUE;MODE=MSSQLServer
                Connection conn = DriverManager.getConnection(connectionBuilder.toString(), "sa", "");
                String sql = getSqlString(scriptUrl);
                PreparedStatement sqlStatement = conn.prepareStatement(sql);
                boolean result = sqlStatement.execute();
                if (result == false) {
                    isSuccessPath = true;
                }
            } catch (Exception ex) {
                logger.debug("[runScript]: Error: " + ex.toString());
                isSuccessPath = false;
            }
        }
        return isSuccessPath;
    }

    private String getSqlString(String path) {

        InputStream inputStream = RunScript.class.getResourceAsStream(path);
        StringBuilder sqlString = new StringBuilder();
        byte b = 0;

        try {
            while (b != -1) {
                b = (byte) inputStream.read();
                sqlString.append((char) b);
            }
            inputStream.close();
        } catch (Exception ex) {
            logger.debug("getSqlString Fail: " + ex.toString());
        }
        return sqlString.toString();
    }

    private boolean isFileExist(String filePath) {
        if (RunScript.class.getResource(filePath) != null) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws ClassNotFoundException, Exception {
        RunScript run = new RunScript();
        run.execute();
    //System.out.println(run.getSqlString("/Database/Script.sql"));
    }
}
